package chap_02_CAS.step_01_Atomic_Base;

import lombok.Data;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description 自己实现一个自旋锁
 * @Author shihan
 * @Date 2022/10/29 18:11
 * @Version 1.0
 */
public class Atomic_02_SpinLockDemo {

    /**
     * 某种程度上讲，这个是 ReentrantLock 思想的雏形（虽然他底层实现是AQS更复杂）
     *
     * @param args
     */
    public static void main(String[] args) {
        MySpinLock mySpinLock = new MySpinLock();

        new Thread(() -> {
            mySpinLock.lock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "执行业务逻辑...");
            mySpinLock.unlock();
        }, "t1").start();

        // 延迟200毫秒，保证上面的线程先执行
        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            mySpinLock.lock();
            System.out.println(Thread.currentThread().getName() + "执行业务逻辑...");
            mySpinLock.unlock();
        }, "t2").start();
    }

}

@Data
class MySpinLock {

    private AtomicReference<Thread> reference = new AtomicReference<>(null);

    /**
     * 加锁
     */
    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "--come in");
        // 当前没有线程，则设置为当前线程，获取锁成功
        // 否则获取失败一直循环尝试获取锁（自旋）
        while (!reference.compareAndSet(null, thread)) {

        }
    }

    /**
     * 释放锁
     */
    public void unlock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "--release out");
        // 获取锁的线程是当前线程本身，则释放锁
        reference.compareAndSet(thread, null);
    }

}
